<?php
function commstack( $input, &$output)
{
    $opres  = "Error. Unexpected internal error.";
    $output = NULL;

    $descriptors = array(
	0 => array("pipe", "r"),  			// stdin is a pipe that the child will read from
	1 => array("pipe", "w"),			// stdout is a pipe that the child will write to
	2 => array("file", "/tmp/commscr.log", "a")	// stderr is a file to write to
    );

$cwd = '/tmp';
//    $cwd = NULL;

$env = array('some_option' => 'aeiou');
//    $env = NULL;

    $docroot = dirname($_SERVER['DOCUMENT_ROOT']);
    $scrname = $docroot.'/lib/commstack/scripts/fw-commstack';

    $proc = proc_open( $scrname, $descriptors, $pipes, $cwd, $env);

//    $proc = proc_open('tcpconnect 127.0.0.1 5398', 
//	    $descriptors, $pipes, $cwd, $env);

    if (is_resource($proc)) {

// $pipes now looks like this:
// 0 => writeable handle connected to child stdin
// 1 => readable handle connected to child stdout
// Any error output will be appended to /tmp/error-output.txt

	for( $i=0; $i<count($input); $i++ ) 
	    fwrite($pipes[0], $input[$i]);
	    
	fclose($pipes[0]);

	$sres =  stream_get_contents($pipes[1]);
	fclose($pipes[1]);

// It is important that you close any pipes before calling
// proc_close in order to avoid a deadlock
	$return_value = proc_close($proc);

	$ares = explode( "\n", $sres );

//    print_r( $ares ); echo "<br>\n";

// Last Line always ampty
	$icount = count($ares)-1;
    
// Last output line must be result code
	$icount--;
	
	if( $icount >= 0 ) {
	    $k = 0;
	    for( $i=0; $i<$icount; $i++ ) {
		$ares[$i] = trim($ares[$i]);
		if( empty($ares[$i])) continue;
		$output[$k] = $ares[$i];
		$k++;
	    }
	    $opres = $ares[$icount];
	}
	else
	    $opres = "Script 'commstack' not return any data.";
    }
    else
	$opres = "Error. Executing script 'commstack'.";

    return $opres;
}
